var http = require("http");
var fs = require("fs");
var url = require("url");
var port = process.argv[2];

if (!port) {
  console.log("请指定端口好不好\n node server.js 8888 这样不会吗？");
  process.exit(1);
}

var server = http.createServer(function (request, response) {
  var parseUrl = url.parse(request.url, true);
  var pathWithQuery = request.url;
  var queryString = "";
  if (pathWithQuery.indexOf("?") >= 0) {
    queryString = pathWithQuery.substring(pathWithQuery.indexOf("?"));
  }
  var path = parseUrl.pathname;
  var query = parseUrl.query;
  var method = request.method;

  console.log("接收请求，路径为：" + pathWithQuery);

  response.statusCode = 200;
  // 默认首页
  const filePath = path === '/' ? '/index.html' : path
  const pointIndex = filePath.lastIndexOf('.')
  // suffix 是后缀
  const suffix = filePath.substring(pointIndex)
  const fileTypes = {
    '.html': 'text/html',
    '.css': 'text/css',
    '.js': 'text/javascript',
    '.png': 'image/png',
    '.jpg': 'image/jpeg'
  }
  response.setHeader("Content-Type", 
    `${fileTypes[suffix] || 'text/index.html'};charset=utf-8`);
  
  let content
  try {
    content = fs.readFileSync(`./public/${filePath}`)
  } catch (error) {
    content = `      
    <!DOCTYPE html>
    <head>
      <link rel="stylesheet" href="/style">
    </head>
    <body>
      <h1>404</h1>
      <h2>你访问的资源不存在</h2>
    </body>`;
    response.statusCode = 400;
  }
  response.write(content);
  response.end();

});

server.listen(port);
console.log(
  "监听 " +
    port +
    " 成功\n请在单杠上做后摆上转体360单手倒立然后另一只手打开 http://localhost:" +
    port
);